import asyncio

from sqlalchemy import insert, desc
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.future import select
from typing import Dict, Any, List

from common.sqlalchemy_db import SqlalchemyX
from common.util import singleton
from modules.mod import Message
from service.GroupDBService import GroupDBService
from service.UserService import UserService


@singleton
class MessageService:
    def __init__(self, session: AsyncSession = SqlalchemyX.AsyncSessionLocal()):
        self.session = session
        self.group_service = GroupDBService()
        self.user_service = UserService()

    async def create_message(self, message_mes: Dict[str, Any]) -> int:
        stmt = insert(Message).values(**message_mes)
        result = await self.session.execute(stmt)
        await self.session.commit()
        return result.inserted_primary_key[0]

    async def find_message_by_option(self, option: Dict[str, Any]) -> List[Message]:
        query = select(Message)

        # 动态构建查询条件
        where_condition = option.get("where", {})

        # 处理 where 是字典的情况
        if isinstance(where_condition, dict):
            for key, value in where_condition.items():
                if hasattr(Message, key):
                    query = query.where(getattr(Message, key) == value)
        # 处理 where 是列表的情况（可能是 OR 条件）
        elif isinstance(where_condition, list):
            from sqlalchemy import or_
            or_conditions = []
            for condition in where_condition:
                if isinstance(condition, dict):
                    for key, value in condition.items():
                        if hasattr(Message, key):
                            or_conditions.append(getattr(Message, key) == value)
            if or_conditions:
                query = query.where(or_(*or_conditions))

        # ... existing code ...
        skip = option.get("skip", 0)
        take = option.get("take", 100)  # 默认每页100条数据
        order_by = option.get("order", {})

        if order_by:
            for key, direction in order_by.items():
                if hasattr(Message, key):
                    query = query.order_by(desc(key) if direction == "DESC" else key)

        query = query.offset(skip).limit(take)
        result = await self.session.execute(query)
        messages = result.scalars().all()
        return messages

    async def get_last_message_by_group(self, option: Dict[str, Any]) -> Message:
        option.update({
            "skip": 0,
            "take": 1
        })
        query = select(Message)
        for key, value in option.items():
            if hasattr(Message, key):
                query = query.where(getattr(Message, key) == value)
        query = query.order_by(Message.message_created_time)
        result = await self.session.execute(query.first())
        return result.scalars().first()

    async def get_default_group_history_messages(self, page: int, limit: int) -> Dict[str, Any]:
        # 获取默认群组
        default_group = await self.group_service.get_default_group()
        default_group_id = default_group.group_id
        # 查找历史消息
        history_mes_limit = await self.find_message_by_option({
            "where": {"message_to_id": default_group_id},
            "order": {"message_created_time": "DESC"},
            "skip": (page - 1) * limit,
            "take": limit
        })
        # 解析历史消息
        resolve_history_message = await self.resolve_history_message(history_mes_limit)
        # 计算总消息数量
        all_message_count = len(await self.find_message_by_option({"message_to_id": default_group_id}))
        return {
            "error_code": 0,
            "data": {
                "curPage": page,
                "messageNum": len(history_mes_limit),
                "pageSum": (all_message_count // limit) + 1,
                "historyMessages": resolve_history_message
            }
        }

    async def resolve_history_message(self, history_messages: List[Message]) -> List[Dict[str, Any]]:
        async def process_message(message: Message) -> Dict[str, Any]:
            # 直接访问 Message 对象的属性
            message_id = message.message_id
            message_from_id = message.message_from_id
            message_to_id = message.message_to_id
            message_type = message.message_type
            message_content = message.message_content
            message_content_type = message.message_content_type
            message_created_time = message.message_created_time
            message_state = message.message_state
            # 私聊
            if message_type == 0:
                message_from_mes = await self.user_service.get_user_basic_mes({"user_id": message_from_id})
                message_to_mes = await self.user_service.get_user_basic_mes({"user_id": message_to_id})
                message_to_mes = {
                    "target_id": message_to_mes["user_id"],
                    "target_name": message_to_mes["user_name"],
                    "target_avatar": message_to_mes["user_avatar"],
                    "target_state": message_to_mes["user_state"]
                }
            else:
                # 群聊
                message_from_mes = await self.user_service.get_user_basic_mes({"user_id": message_from_id})
                message_to_mes = await self.group_service.get_group_mes({"group_id": message_to_id})
                message_to_mes = {
                    "target_id": message_to_mes.group_id,
                    "target_name": message_to_mes.group_name,
                    "target_avatar": message_to_mes.group_avatar,
                    "target_state": 1
                }
            message_from_mes = {
                "from_id": message_from_mes["user_id"],
                "from_name": message_from_mes["user_name"],
                "from_avatar": message_from_mes["user_avatar"],
                "from_state": message_from_mes["user_state"]
            }
            return {
                "message_id": message_id,
                "message_from_mes": message_from_mes,
                "message_to_mes": message_to_mes,
                "message_type": message_type,
                "message_content": message_content,
                "message_content_type": message_content_type,
                "message_created_time": message_created_time,
                "message_state": message_state
            }

        # 并行处理所有消息
        tasks = [process_message(message) for message in history_messages]
        resolved_messages = await asyncio.gather(*tasks)
        return resolved_messages